import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
import { getToken } from '@/utils/token.js'
// 导入组件
// import Layout from '@/views/Layout/Layout.vue'
// import Login from '@/views/Login/index.vue'
// import Home from '@/views/Home/index.vue'
// import User from '@/views/User/index.vue'
// import Search from '@/views/Search/index.vue'
// import SearchResult from '@/views/Search/SearchResult.vue'
// import ArticleDetail from '@/views/ArticleDetail/index.vue'
// import Edit from '@/views/Edit/index.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout" */ '@/views/Layout/Layout.vue'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */ '@/views/Home/index.vue'),
        meta: { scrollTop: '' }
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */ '@/views/User/index.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/Login/index.vue'),
    beforeEnter: (to, from, next) => {
      console.log(router)
      // 需求：登录成功后，不允许切换到登录页面
      // 分析：跳转页面为登录页且已经登录（token存在）
      if (getToken()) {
        // 留在当前页面原地
        // next(false)
        // 想要进登录页不留在原地了，而是返回首页
        // 手机App里没有地址栏，你是不能破坏跳转的过程的,所以不用深究这个过程
        next('/layout/home')
      } else {
        // 放行（允许跳转）
        next()
      }
    }
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search/index.vue')
  },
  {
    path: '/searchResult/:keyword',
    component: () =>
      import(/* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult.vue')
  },
  {
    path: '/articleDetail',
    component: () =>
      import(/* webpackChunkName: "ArticleDetail" */ '@/views/ArticleDetail/index.vue')
  },
  {
    path: '/edit',
    component: () => import(/* webpackChunkName: "Edit" */ '@/views/Edit/index.vue')
  }
]

const router = new VueRouter({
  routes
})

// 路由全局守卫
router.beforeEach((to, from, next) => {
  console.log(router)
  // console.log(router.currentRoute.fullPath)
  console.log(to.fullPath)
  const currentRoute = to.fullPath
  // 只有token存在才会存储页面路由
  if (getToken()) {
    // 存储当前页面的路由地址到vuex
    store.commit('getRouterUrl', currentRoute)
  }

  next()
})

export default router
